<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单编号" prop="totalPrice">
              <el-input v-model="queryParams.id" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="住房编号" prop="totalPrice">
              <el-input v-model="queryParams.roomNo" placeholder="请输入住房编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="酒店" prop="hotelId">
              <el-select
                v-model="queryParams.hotelId"
                filterable
                clearable
                placeholder="请选择酒店"
                :loading="loading"
                @change="handleRoomQueryChange"
              >
                <el-option v-for="item in options" :key="item.id" :label="item.hotelName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="房型" prop="roomId">
              <el-select v-model="queryParams.roomId" filterable clearable placeholder="请选择房型" :loading="loading">
                <el-option v-for="item in roomOptions" :key="item.id" :label="item.roomType" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
                <el-option label="待支付" :value="0" />
                <el-option label="已确认" :value="1" />
                <el-option label="已入住" :value="2" />
                <el-option label="已退房" :value="3" />
                <el-option label="已过期" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker clearable v-model="queryParams.startDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择入住开始日期" />
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker clearable v-model="queryParams.endDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择入住结束日期" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['hotel:hotelOrders:edit']">客人入住</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hotel:hotelOrders:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="hotelOrdersList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单编号" align="center" prop="id" v-if="true" width="240px" />
        <el-table-column label="住房编号" align="center" prop="roomNo" v-if="true" />
        <el-table-column label="" align="center" prop="userId" v-if="false" />
        <el-table-column label="" align="center" prop="roomId" v-if="false" />
        <el-table-column label="" align="center" prop="hotelId" v-if="false" />
        <el-table-column label="入住人" align="center" prop="name" />
        <el-table-column label="入住开始日期" align="center" prop="startDate" />
        <el-table-column label="入住结束日期" align="center" prop="endDate" />
        <el-table-column label="订单总价" align="center" prop="totalPrice">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.totalPrice) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="预计收入" align="center" prop="revenue">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.revenue) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="预付金额" align="center" prop="prepayAmount">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.prepayAmount) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center" prop="paymentMethod" />
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template #default="scope">
            <dict-tag :options="ter_hotel_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="入住人电话" align="center" prop="mobile" />
        <el-table-column label="身份证图片" align="center" prop="idCardurlUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.idCardurlUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="钥匙id" align="center" prop="keyId" v-if="false" />
        <el-table-column label="门锁密钥" align="center" prop="doorKey" v-if="false" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="退款" placement="top">
              <el-button
                link
                type="primary"
                icon="CreditCard"
                :disabled="scope.row.orderStatus === 0 || scope.row.orderStatus === 4"
                @click="handleDelete(scope.row)"
                v-hasPermi="['tearoom:order:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改酒店订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="hotelOrdersFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="住房编号" prop="roomNo">
          <el-input v-model="form.roomNo" placeholder="请输入住房编号" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态" clearable>
            <el-option label="已入住" :value="2" />
            <el-option label="已退房" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证图片" prop="idCardurl">
          <image-upload v-model="form.idCardurl" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HotelOrders" lang="ts">
import { listHotelOrders, getHotelOrders, addHotelOrders, updateHotelOrders, orderRefund } from '@/api/hotel/hotelOrders';
import { HotelOrdersVO, HotelOrdersQuery, HotelOrdersForm } from '@/api/hotel/hotelOrders/types';
import { selectCombByHotel } from '@/api/hotel/hotelRooms';
import { HotelRoomsVO } from '@/api/hotel/hotelRooms/types';
import { selectComb } from '@/api/hotel/hotels';
import { HotelsVO } from '@/api/hotel/hotels/types';
import { floatToFixed2 } from '@/utils/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ter_hotel_status } = toRefs<any>(proxy?.useDict('ter_hotel_status'));
const roomOptions = ref<HotelRoomsVO[]>([]);
const options = ref<HotelsVO[]>([]);
const hotelOrdersList = ref<HotelOrdersVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const hotelOrdersFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: HotelOrdersForm = {
  id: undefined,
  userId: undefined,
  roomId: undefined,
  hotelId: undefined,
  startDate: undefined,
  endDate: undefined,
  totalPrice: undefined,
  orderStatus: undefined,
  prepayAmount: undefined,
  mobile: undefined,
  couponId: undefined,
  paymentMethod: undefined,
  isRenew: undefined,
  couponPrice: undefined,
  couponHour: undefined,
  revenue: undefined,
  keyId: undefined,
  doorKey: undefined,
  renewId: undefined,
  idCardurl: undefined,
  roomNo: undefined,
  refundId: undefined
}
const data = reactive<PageData<HotelOrdersForm, HotelOrdersQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    roomId: undefined,
    hotelId: undefined,
    startDate: undefined,
    endDate: undefined,
    totalPrice: undefined,
    orderStatus: undefined,
    prepayAmount: undefined,
    mobile: undefined,
    couponId: undefined,
    paymentMethod: undefined,
    isRenew: undefined,
    couponPrice: undefined,
    couponHour: undefined,
    revenue: undefined,
    keyId: undefined,
    doorKey: undefined,
    renewId: undefined,
    refundId: undefined,
    idCardurl: undefined,
    roomNo: undefined,
    params: {
    }
  },
  rules: {
    roomNo: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    orderStatus: [
      { required: true, message: "不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const fetchData = async () => {
  loading.value = true;
  const response = await selectComb();
  options.value = response.data;
  loading.value = false;
};
/** 查询酒店订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listHotelOrders(queryParams.value);
  console.log(res);
  hotelOrdersList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  hotelOrdersFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
async function handleRoomQueryChange(value: number | string) {
  if(queryParams.value.hotelId.length>0){
    const response = await selectCombByHotel(queryParams.value.hotelId);
    roomOptions.value = response.data;
  }
  queryParams.value.roomId = '';
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HotelOrdersVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HotelOrdersVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getHotelOrders(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改酒店订单";
}

/** 提交按钮 */
const submitForm = () => {
  hotelOrdersFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateHotelOrders(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addHotelOrders(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: HotelOrdersVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认退回订单编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  Object.assign(form.value, row);
  await orderRefund(form.value);
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('hotel/hotelOrders/export', {
    ...queryParams.value
  }, `hotelOrders_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  fetchData();
});
</script>
